package mil.af.amc.adpetracker.dao.hibernate;

import mil.af.amc.adpetracker.dao.ManufacturerDao;
import mil.af.amc.adpetracker.model.EquipmentType;
import mil.af.amc.adpetracker.model.ItemModel;
import mil.af.amc.adpetracker.model.Manufacturer;
import org.hibernate.Criteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

/**
 * Hibernate Manufacturer DAO implementation
 *
 * @author TSgt Jason Ferguson
 */
@Repository("manufacturerDao")
public class HibernateManufacturerDao extends HibernateGenericDao<Manufacturer> implements ManufacturerDao {

    public HibernateManufacturerDao() {
        super(Manufacturer.class);
    }

    @SuppressWarnings({"unchecked", "ForLoopReplaceableByForEach"})
    public List<Manufacturer> getManufacturerByEquipmentType(EquipmentType type) {

        Criteria imCriteria = sessionFactory.getCurrentSession().createCriteria(ItemModel.class);
        Criteria etCriteria = imCriteria.createCriteria("type");
        etCriteria.add(Restrictions.eq("id", type.getId()));

        List<ItemModel> itemModelList = imCriteria.list();

        Set<Manufacturer> manufacturerSet = new TreeSet<Manufacturer>();
        for (ItemModel itemModel: itemModelList) {
            manufacturerSet.add(itemModel.getManufacturer());
        }

        return new ArrayList<Manufacturer>(manufacturerSet);

//        DetachedCriteria crit = DetachedCriteria.forClass(ItemModel.class);
//        DetachedCriteria typeCrit = crit.createCriteria("type");
//        typeCrit.add(Restrictions.eq("id", type.getId()));
//        List<ItemModel> modelList = (List<ItemModel>) getHibernateTemplate().findByCriteria(crit);
//
//        List<Manufacturer> manufacturerList = new ArrayList<Manufacturer>();
//        for (Iterator<ItemModel> it = modelList.iterator(); it.hasNext();) {
//            ItemModel model = it.next();
//            if (!manufacturerList.contains(model.getManufacturer())) {
//                Manufacturer manu = model.getManufacturer();
//                if (manu!=null && manu.getName() != null) {
//                    manufacturerList.add(model.getManufacturer());
//                }
//            }
//        }
//
//        Collections.sort(manufacturerList);
//        return manufacturerList;

    }
}
